package com.whjfxx.terminal.biz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whjfxx.terminal.biz.enums.SignType;
import com.whjfxx.terminal.biz.mapper.AccountMapper;
import com.whjfxx.terminal.biz.service.AccountService;
import com.whjfxx.terminal.entity.Account;
import com.whjfxx.terminal.entity.User;
import com.whjfxx.terminal.exceptions.BizException;
import com.whjfxx.terminal.utils.CodeUtil;
import com.whjfxx.terminal.utils.MD5Util;
import com.whjfxx.terminal.utils.MyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by b.c on 2022/4/14 10:23
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Override
    public Account getPasswordUserByUserId(Long userId) {
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Account::getUserId, userId);
        wrapper.eq(Account::getType, SignType.password.name());
        return this.getOne(wrapper);
    }

    @Override
    public List<Account> getPasswordUserByUserIds(List<Long> userIds) {
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper();
        wrapper.in(Account::getUserId, userIds);
        wrapper.eq(Account::getType, SignType.password.name());
        return super.list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addPasswordUser(String accountNo, String password, User user) {
        Account account = new Account();
        account.setAccountNo(accountNo);
        account.setPassword(MD5Util.encode(password));
        account.setType(SignType.password.name());
        account.setCreateTime(new Date());
        account.setUpdateTime(new Date());
        account.setUserId(user.getId());
        this.save(account);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(Long userId) {
        Account account = getPasswordUserByUserId(userId);
        if (ObjectUtil.isNull(account)) {
            throw BizException.build("用户账号信息不存在");
        }
        // 随机密码
        String newPwd = CodeUtil.genPwd(8);
        String newPwdMd5 = MD5Util.encode(newPwd);
        account.setPassword(newPwdMd5);
        int i = this.baseMapper.updateById(account);
        MyUtil.validUpdate(i);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByUserIds(List<Long> userIds) {
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper();
        wrapper.in(Account::getUserId, userIds);
        this.remove(wrapper);
    }

}
